package com.car.file;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.nio.ByteBuffer;

import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

 

public class FileUtil {
	// 锁
	static ReadWriteLock lock = new ReentrantReadWriteLock();
	// 值
	double value = 0d;
	int addtimes = 0;

	public static void copyNio(File source, File target) {
		FileChannel ch1 = null;
		FileChannel ch2 = null;
		FileInputStream fin = null;
		FileOutputStream fout = null;
		try {

			fin = new FileInputStream(source);

			fout = new FileOutputStream(target);

			ByteBuffer buffer = ByteBuffer.allocate(512);

			ch1 = fin.getChannel();

			ch2 = fout.getChannel();

			while (ch1.read(buffer) != -1) { // 从通道中读取内容到缓冲区

				buffer.flip(); // 让缓冲区回到初始位置才能进行写操作

				ch2.write(buffer);

				buffer.clear(); // 清空缓冲区

			}

			ch1.close();

			ch2.close();

			fin.close();

			fout.close();

		}

		catch (FileNotFoundException e) {

			e.printStackTrace();

		} catch (IOException e) {

			e.printStackTrace();

		} catch (Exception e) {

			e.printStackTrace();

		} finally {
			try {
				ch1.close();
				ch2.close();

				fin.close();

				fout.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

	}

	/**
	 * 
	 * @param source
	 * @param targetDir
	 *            以地区，车牌号以文件名
	 */
	public static void writeNio(FileInputStream input, String targetDir) {
		FileChannel ch1 = null;

		FileChannel ch2 = null;
		FileOutputStream fout = null;
		try {
			// new File("d:\\efg.txt");
			File targetFile = new File(targetDir);
			fout = new FileOutputStream(targetFile);

			ByteBuffer buffer = ByteBuffer.allocate(512);

			ch1 = input.getChannel();

			ch2 = fout.getChannel();

			while (ch1.read(buffer) != -1) { // 从通道中读取内容到缓冲区

				buffer.flip(); // 让缓冲区回到初始位置才能进行写操作

				ch2.write(buffer);

				buffer.clear(); // 清空缓冲区

			}

		}

		catch (FileNotFoundException e) {

			e.printStackTrace();

		} catch (IOException e) {

			e.printStackTrace();

		} catch (Exception e) {

			e.printStackTrace();

		} finally {
			try {
				ch1.close();
				ch2.close();
				input.close();
				fout.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

	}

	/**
	 * 
	 * @param source
	 * @param targetDir
	 * 以地区，车牌号以文件名
	 * 未来可以实现断点续写
	 */
	public static void write(InputStream input, String targetDir) {
		Lock writeLock = lock.writeLock();
		writeLock.lock();
		System.out.println("ReadWriteLock  to addValue:     "
				+ System.currentTimeMillis());
		FileOutputStream out = null;

		try {
			// new File("d:\\efg.txt");
			File targetFile = new File(targetDir);
			out = new FileOutputStream(targetFile);
			int chByte = input.read();
			while (chByte != -1) { //  
				out.write(chByte);
				chByte = input.read();
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();

		} catch (IOException e) {
			e.printStackTrace();

		} catch (Exception e) {
			e.printStackTrace();

		} finally {
			try {
				input.close();
				out.flush();
				out.close();
				// 释放writeLock锁
				writeLock.unlock();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

	}
    /**
     * path下面挖一级目录
     * @param path
     * @return
     */
	public static List<File> loadFiles(String path) {
		List<File> fileArray = new ArrayList<File>();
		int fileIndex = 1;
		File file = new File(path);
		
		if (file.isDirectory()) {
			System.out.println("==目录==" + file.getName());
			String[] fileList = file.list();
			for (int i = 0; i < fileList.length; i++) {
				String bfile=fileList[i];
				File onefile=new File(bfile);
				if(onefile.isDirectory()){
				fileArray.addAll(getDir(path + "\\" + onefile.getName()));
				}
				else if (onefile.isFile()) {
			/*		System.out.println("path=" + file.getPath());
					System.out
							.println("absolutepath=" + file.getAbsolutePath()+i);
					System.out.println("name=" + file.getName());*/
					fileArray.add(onefile);
					System.out.println("读取文件成功" + fileIndex++);
				}else{
					fileArray.add(onefile);
					System.out.println("特殊读取文件成功" + fileIndex++); 
				}
			}
		}
		return fileArray;
	}
	public static List loadFiles2(String path) {
		List<File> fileArray = new ArrayList<File>();
		int fileIndex = 1;
		File file = new File(path);
		
		if (file.isDirectory()) {
			System.out.println("==目录==" + file.getName());
			String[] fileList = file.list();
			for (int i = 0; i < fileList.length; i++) {
				if(file.isDirectory()){
					loadFiles2(path + "\\" + fileList[i]);
				}
				
				if (file.isFile()) {
					System.out.println("path=" + file.getPath());
					System.out
							.println("absolutepath=" + file.getAbsolutePath()+i);
					System.out.println("name=" + file.getName());
					fileArray.add(file);
					System.out.println("读取文件成功" + fileIndex++);
				}
			}
		}
		return fileArray;
	}

	private static List getDir( String path) {
		List fileList=new ArrayList();
		File file=new File(path);
		String[] files = file.list();
		for (int i = 0; i < files.length; i++) {
			file = new File(path + "\\" + files[i]);
			                                
			if (file.isFile()) {
				System.out.println("path=" + file.getPath());
				System.out.println("absolutepath=" + file.getAbsolutePath());
				System.out.println("name=" + file.getName());
				fileList.add(file);
				System.out.println("读取文件成功" );
			}
			
		}
		return fileList;
	}
	/**

	　　* 写文件  避免中文乱码。

	　　*

	　　* @param filePathAndName   String  写文件路径

	　　* @param fileContent   String  需要写入的内容

	　　*/

	public static void writeFile(String filePathAndName, String fileContent) {

	try {

	File f = new File(filePathAndName);

	if (!f.exists()) {

	f.createNewFile();

	}

	OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f),"UTF-8");

	BufferedWriter writer=new BufferedWriter(write);

	//PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(filePathAndName)));

	//PrintWriter writer = new PrintWriter(new FileWriter(filePathAndName));

	writer.write(fileContent);

	writer.close();

	} catch (Exception e) {

	System.out.println("写文件内容操作出错");

	e.printStackTrace();

	}

	}



	/**

	* 读取文件内容

	*	避免中文乱码。

	* @param filePathAndName   String  读取文件路径

	* @return String  文件中的内容

	*/

	public static String readFile(String filePathAndName) {

	String fileContent = "";

	try {

	File f = new File(filePathAndName);

	if(f.isFile()&&f.exists()){

	InputStreamReader read = new InputStreamReader(new FileInputStream(f),"UTF-8");

	BufferedReader reader=new BufferedReader(read);

	String line;

	while ((line = reader.readLine()) != null) {

	fileContent += line;

	}

	read.close();

	}

	} catch (Exception e) {

	System.out.println("读取文件内容操作出错");

	e.printStackTrace();

	}

	return fileContent;

	}

 
}
